import React, { Component } from 'react';
import { Button, Modal, Form, PageHeader, Badge, Radio, Table, Row, Col, Icon, message, Popover } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { TableCustomize } from '../Components/TableCustomize'
import { BasicPagination, isInvalidObject, compareNum, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
// import { withPermission } from '../../../components/withpermission';
import AddForm from './AddForm';
import AddForm2 from './AddForm2';
import AddForm3 from './AddForm3';
import { checkResultList } from '../../../utils/global';
import * as CheckManagementService from '../../../axios/CheckManagement'
import * as APIServiceFile from '../../../axios/File'
import { withRouter } from 'react-router';
// const CreateButton = withPermission(Button, 'create')
const { confirm } = Modal
const FormItem = Form.Item;

class CheckManagement_details extends Component {
	state = {
		resultList: [
			{ key: 0, label: '新建' },
			{ key: 1, label: '合格' },
			{ key: 2, label: '不合格' },
			{ key: 3, label: '不适用' },
		],
		columns: [],
		columns1: [
			{
				title: '序号',
				dataIndex: 'id',
				width: 50,
				align: 'center',
				render: (text, record, index) => `${index + 1}`,
			},

			{
				title: '类别',
				width: 100,
				dataIndex: 'checkTypeSecond',
				sorter: (a, b) => compareString(a.checkTypeSecond, b.checkTypeSecond)
			},
			{
				title: '检验项',
				width: 150,
				// allowEllipsis: true,
				dataIndex: 'checkItemName',
				sorter: (a, b) => compareString(a.checkItemName, b.checkItemName)
			},
			{
				title: '标准值',
				width: 100,
				dataIndex: 'contain',
				sorter: (a, b) => compareString(a.contain, b.contain)
			},
			{
				title: '备注',  // 第二类别所属分类
				// width: 100,
				dataIndex: 'remarks',
				sorter: (a, b) => compareString(a.remarks, b.remarks)
			},
			{
				title: '图片',
				width: 130,
				dataIndex: 'fileIds',
				render: (text, record, index) => {
					return text.length > 0 ? <a onClick={() => this.showPicture(text)}>查看图片</a> : '无图片'
				}
			},
			{
				title: '检验结果',
				width: 100,
				dataIndex: 'result',
				sorter: (a, b) => compareNum(a.result, b.result),
				render: (text) => {
					let obj = this.state.resultList.find(item => item.key == text)
					return obj?.label
				}
			},
			{
				title: '纠正措施',
				width: 200,
				dataIndex: 'correctiveAction',
				sorter: (a, b) => compareNum(a.correctiveAction, b.correctiveAction),
			},
			{ dataIndex: '' }
		],
		locationData: {},
		detailsData: {},
		searchItemFather: {},
		pictureVisiable: false,
		pictureData: [],
		previewImage: [],
		previewVisible: false
	};
	componentDidMount() {
		console.log(this.props.location.data, 'this.props.location.data')
		this.setState({
			locationData: this.props.location.data ? this.props.location.data.record : JSON.parse(localStorage.getItem('CheckManagement_detailsList')),
			detailsData: this.props.location.data ? this.props.location.data.record.details : JSON.parse(localStorage.getItem('CheckManagement_detailsList')).details,
			searchItemFather: this.props.location.data ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('CheckManagement_searchItem')),
		}, this.getColumns)
	}
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}

	// 拼接表格列
	getColumns = () => {
		let data = this.state.detailsData?.checkDetails
		let len = {}, dataSource = []
		for (let item of data) {
			if (!len[item.checkTypeSecond]) {
				let checkTypeSecond = item.checkTypeSecond
				let index = 0
				for (let item1 of data) {
					if (item1.checkTypeSecond == checkTypeSecond) {
						dataSource.push(item1)
						index++
					}
				}
				len[checkTypeSecond] = index
			}
		}

		let oldText = ''
		let columns = [
			{
				title: '序号',
				dataIndex: 'id',
				width: 50,
				align: 'center',
				render: (text, record, index) => `${index + 1}`,
			},

			{
				title: '类别',
				width: 100,
				ellipsis: true,
				dataIndex: 'checkTypeSecond',
				align:'center',
				sorter: (a, b) => compareString(a.checkTypeSecond, b.checkTypeSecond),
				render: (text, record, index) => {
					const obj = {
						children: text,
						props: {},
					};

					if (index == 0) {
						oldText = text
						obj.props.rowSpan = len[text];
					} else if (oldText != text) {
						oldText = text
						obj.props.rowSpan = len[text];
					} else {
						obj.props.rowSpan = 0;
					}
					return obj;
				},
			},
			{
				title: '检验项',
				width: 230,
				ellipsis: true,
				// allowEllipsis: true,
				dataIndex: 'checkItemName',
				// sorter: (a, b) => compareString(a.checkItemName, b.checkItemName)
			},
			{
				title: '标准值',
				width: 100,
				ellipsis: true,
				dataIndex: 'contain',
				// sorter: (a, b) => compareString(a.contain, b.contain)
			},
			{
				title: '图片',
				width: 130,
				ellipsis: true,
				dataIndex: 'fileIds',
				render: (text, record, index) => {
					return text.length > 0 ? <a onClick={() => this.showPicture(text)}>查看图片</a> : '无图片'
				}
			},
			{
				title: '检验结果',
				width: 100,
				ellipsis: true,
				dataIndex: 'result',
				// sorter: (a, b) => compareNum(a.result, b.result),
				render: (text) => {
					let obj = this.state.resultList.find(item => item.key == text)
					return obj?.label
				}
			},
			{
				title: '纠正措施',
				width: 230,
				ellipsis: true,
				dataIndex: 'correctiveAction',
				// sorter: (a, b) => compareNum(a.correctiveAction, b.correctiveAction),
				render: (text) => {
					const content = (
						<div>
							{text}
						</div>
					);
					return <Popover content={content} title="备注">
						<span>{text}</span>
					</Popover>
				}
			},
			{
				title: '备注',  // 第二类别所属分类
				// width: 200,
				dataIndex: 'remarks',
				ellipsis: true,
				// sorter: (a, b) => compareString(a.remarks, b.remarks),
				render: (text) => {
					const content = (
						<div>
							{text}
						</div>
					);
					return <Popover content={content} title="备注">
						<span>{text}</span>
					</Popover>
				}
			},
			{ dataIndex: '' }
		]

		this.setState({ columns, dataSource })
	}

	showPicture = async (fileIds) => {
		let imgs = []
		for (let i = 0; i < fileIds.length; i++) {
			let res = await APIServiceFile.queryFileId(fileIds[i])
			let data = res.data.data
			imgs.push(data)
		}
		console.log(imgs, 'imgs');
		if (imgs.length > 0) {
			this.setState({
				pictureVisiable: true,
				pictureData: imgs
			})
		} else {
			openModalMessage('warning', '该检验项无图片')
		}
	}
	// 查看大图
	showBigPicture = (index) => {
		this.setState({
			previewVisible: true,
			previewImage: { tomcatPath: this.state.pictureData[index].tomcatPath, index }
		})
	}
	// 前后切换图片
	checkPicture = (type) => {
		const { previewImage, pictureData } = this.state
		let index = previewImage.index
		if (type == 'pre') {
			if (index == 0) {
				message.warning('当前为第一张图片')
				return
			}
			index--
		} else if (type == 'next') {
			if (index == pictureData.length - 1) {
				message.warning('当前为最后一张图片')
				return
			}
			index++
		}
		this.setState({
			previewImage: { tomcatPath: pictureData[index].tomcatPath, index }
		})
	}

	render() {
		const { selectedRowKeys, locationData, detailsData, loading, columns, dataSource, searchItemFather, pictureVisiable, pictureData, previewImage, previewVisible } = this.state;

		const rowSelection = {
			type: 'checkbox',
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys,
				})
			},
			onSelectAll: (selected, selectedRows, changeRows) => {
				const keys = [... this.state.selectedRowKeys];
				const rows = [... this.state.selectedRows];
				if (selected) {
					changeRows.forEach(row => {
						if (isInvalidObject(keys.find(key => key === row.id))) {
							keys.push(row.id);
							rows.push(row);
						}
					})
				} else {
					changeRows.forEach(row => {
						keys.splice(keys.indexOf(row.id), 1);
						rows.splice(rows.indexOf(row), 1);
					})
				}
				this.setState({ selectedRows: rows, selectedRowKeys: keys })
			}
		}
		const formItemLayout = {
			// 抽屉里面Form。二列的布局比例
			labelCol: {
				span: 8
			},
			wrapperCol: {
				span: 8
			}
		};

		return (
			<div>
				<BasicLayoutSearch>
					<PageHeader
						style={{ padding: '4px 24px' }}
						onBack={() => this.props.history.push({ pathname: '/CheckManagement', data: searchItemFather })}
						title={`质检详情`}>
					</PageHeader>
				</BasicLayoutSearch>
				<BasicLayout buttons={[]} name={`检验项`} icon="table">
					<Form>
						<Row>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>生产批号</span>}>
									<div>{detailsData?.batchNo}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>产品机型</span>}>
									<div>{detailsData?.model}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>车间</span>}>
									<div>{detailsData?.workshop}</div>
								</FormItem>
							</Col>
						</Row>
						<Row>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>装配班组</span>}>
									<div>{detailsData?.assemblyTeam}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>装配机位</span>}>
									<div>{detailsData?.assemblyOfReservation}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>装配完成时间</span>}>
									<div>{detailsData?.assemblyCompletionTime}</div>
								</FormItem>
							</Col>
						</Row>
						<Row>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>试机班组</span>}>
									<div>{detailsData?.commissioningTeam}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>试机完成时间</span>}>
									<div>{detailsData?.commissioningCompletionTime}</div>
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} style={{ marginBottom: 0 }} label={<span style={{ fontWeight: 'bold' }}>质检人员</span>}>
									<div>{detailsData?.assignName}</div>
								</FormItem>
							</Col>
						</Row>
					</Form>
					{/* <TableCustomize
						columns={this.state.columns1}
						rowKey={(record) => record.id}
						rowSelection={rowSelection}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						allowEditable={this.loadData}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row8'])
						}}
					/> */}
					<Table
						loading={loading}
						style={{ position: 'relative', overflow: 'auto', width: '100%' }}
						columns={columns}
						dataSource={dataSource}
						rowKey={(record) => record.id}
						bordered
						pagination={false}
						size="small"
						scroll={{x: 1000, y: 500}}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row8'])
						}}
					>
					</Table>
				</BasicLayout>
				<Modal
					title='查看图片'
					visible={pictureVisiable}
					width={'50%'}
					footer={null}
					onCancel={() => this.setState({ pictureVisiable: false })}
				>
					<Row type="flex" justify="space-around" align="center">
						{
							pictureData && pictureData.length > 0 ? pictureData.map((item, index) => {
								return <Col span={6} style={{ border: '1px solid #cfcfcf' }}><img src={item.tomcatPath} key={item.fileId} style={{ width: '100%', height: 200 }} onClick={() => this.showBigPicture(index)} /></Col>
							}) : <Col>无数据</Col>
						}
					</Row>
				</Modal>
				<Modal width={'30%'} visible={previewVisible} footer={null} onCancel={() => this.setState({ previewVisible: false })} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
					<Icon type="left" style={{ fontSize: 40, marginRight: 10 }} onClick={() => this.checkPicture('pre')} />
					<img style={{ width: 'calc(100% - 100px)' }} src={previewImage.tomcatPath} />
					<Icon type="right" style={{ fontSize: 40, marginLeft: 10 }} onClick={() => this.checkPicture('next')} />
				</Modal>
			</div>
		);
	}
}
export default Form.create()(withRouter(CheckManagement_details));